import json
import subprocess
from fabric import Connection
from .wrapper import *


@handle_execute_commnad_remotely
def execute_command_on_node(node, command):
    """在执行节点上执行命令

    Args:
        node (tuple): 执行节点
        command (str): 待执行命令行
    """
    ssh_command = f'ssh {node[1]}@{node[0]} "{command}"'
    subprocess.run(ssh_command, shell=True, check=True)


def execute_step_on_node(node, plugin, params=None, step=None):
    """使用python方式执行测试步骤

    Args:
        node (tuple): 执行节点
        plugin (str): 执行脚本
        params (json, optional): 执行参数. Defaults to None.
        step (list, optional): 执行步骤. Defaults to None.
    """
    command = f'python3 {plugin}'
    if params is not None:
        command += f' -p {params}'
    if step is not None:
        command += f' -s "{step}"'
    print(f'command:{command}')
    result = Connection(node[0], user=node[1]).run(command, hide=True)
    return result.stdout.strip()
